package com.study.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;


/**
 * 
 * @author all
 * @version 1.0
 */
public class DateUtil {
  
  public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";

  public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";

  public static final String FORMAT_THREE = "yyyyMMddHHmmss";
  
  public static final String FORMAT_FOUR = "yyyyMMdd";
  
  public static final String FORMAT_FIVE = "yyyy/MM/dd HH:mm:ss";

  public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";

  public static final String SHORT_DATE_FORMAT = "MM-dd";

  public static final String LONG_TIME_FORMAT = "HH:mm:ss";

  public static final int SUB_YEAR = Calendar.YEAR;

  public static final int SUB_MONTH = Calendar.MONTH;

  public static final int SUB_DAY = Calendar.DATE;

  public static final int SUB_HOUR = Calendar.HOUR;

  public static final int SUB_MINUTE = Calendar.MINUTE;

  public static final int SUB_SECOND = Calendar.SECOND;


  /**
   * 
   * @param dateStr
   * @return
   */
  public static Date StringtoDate(String dateStr, String format) {
    Date d = null;
    SimpleDateFormat formater = new SimpleDateFormat(format);
    try {
      formater.setLenient(false);
      d = formater.parse(dateStr);
    } catch (Exception e) {
      d = null;
    }
    return d;
  }
  /**
 * @param dateStr
 * @param format
 * @param viewFormat
 * @return
 */
public static String stringToDateString(String dateStr, String format,String viewFormat){
	  Date d = StringtoDate(dateStr,format);
	  return DateToString(d,viewFormat);
  }
  public static String stringToDateString(String dateStr, String format){
	  Date d = StringtoDate(dateStr,"yyyyMMdd");
	  return DateToString(d,format);
  }

    public static Date getBeforeDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        return date;
    }
  /**
   */
  public static Date StringtoDate(String dateStr, String format,
      ParsePosition pos) {
    Date d = null;
    SimpleDateFormat formater = new SimpleDateFormat(format);
    try {
      formater.setLenient(false);
      d = formater.parse(dateStr, pos);
    } catch (Exception e) {
      // orderlog.error(e);
      d = null;
    }
    return d;
  }

  /**
   *
   * @param date
   * @return
   */
  public static String DateToString(Date date, String format) {
    String result = new String();
    SimpleDateFormat formater = new SimpleDateFormat(format);
    try {
      result = formater.format(date);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  /**
   * @param format
   * @return
   */
  public static String getCurrDate( String format) {
    return DateToString(new Date(),format).trim();
  }
  /**
   * @param format
   * @return
   */
  public static String getAddDate(int addday, String format) {
      Date dt=new Date();
      dt.setDate(dt.getDate()+addday);
	  return DateToString(dt,format).trim();
  }
  /**
   * @param format
   * @return
   */
  public static String getAddDate(String addday, String format) {
	  int day = Integer.parseInt(addday);
      Date dt=new Date();
      dt.setDate(dt.getDate()+day);
	  return DateToString(dt,format).trim();
  }
  /**
   * 
   * @param dateStr
   * @param amount
   * @return
   */
  public static String DateSub(int dateKind, String dateStr, int amount,String format) {
        Date date = StringtoDate(dateStr, format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(dateKind, amount);
    return DateToString(calendar.getTime(), format);
  }
  
  /**
   * 
   * @param firstTime
   * @param secTime
   */
  public static long TimeSub(String firstTime, String secTime) {
    long first = StringtoDate(firstTime, FORMAT_ONE).getTime();
    long second = StringtoDate(secTime, FORMAT_ONE).getTime();
    return (second - first) / 1000;
  }

  /**
   * 
   * @param year
   *          int
   * @param month
   *          int
   * @return int
   */
  public static int getDaysOfMonth(String year, String month) {
    int days = 0;
    if (month.equals("1") || month.equals("3") || month.equals("5")
        || month.equals("7") || month.equals("8") || month.equals("10")
        || month.equals("12")) {
      days = 31;
    } else if (month.equals("4") || month.equals("6") || month.equals("9")
        || month.equals("11")) {
      days = 30;
    } else {
      if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
          || Integer.parseInt(year) % 400 == 0) {
        days = 29;
      } else {
        days = 28;
      }
    }

    return days;
  }

  /**
   * 
   * @param year
   *          int
   * @param month
   * @return int
   */
  public static int getDaysOfMonth(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month - 1, 1);
    return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  }

  /**
   * 
   * @return int
   */
  public static int getToday() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.DATE);
  }

  /**
   * 
   * @return int
   */
  public static int getToMonth() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.MONTH) + 1;
  }

  /**
   * 
   * @return int
   */
  public static int getToYear() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.YEAR);
  }

  /**
   * 
   * @param date
   *          Date
   * @return int
   */
  public static int getDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.DATE);
  }
  /**
   * 
   * @param date
   *          Date
   * @return int
   */
  public static int getYear(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.YEAR);
  }

  /**
   * 
   * @param date
   *          Date
   * @return int
   */
  public static int getMonth(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.MONTH) + 1;
  }

  /**
   * 
   * @param date1
   *          Date
   * @param date2
   *          Date
   * @return long
   */
  public static long dayDiff(Date date1, Date date2) {
    return (date2.getTime() - date1.getTime()) / 86400000;
  }
  /**
   * @param before
   * @param after
   * @return
   */
  public static int yearDiff(String before,String after) {
      Date beforeDay = StringtoDate(before,LONG_DATE_FORMAT);
      Date afterDay  = StringtoDate(after,LONG_DATE_FORMAT);
      return getYear(afterDay)-getYear(beforeDay);
  }
  /**
   * @param after
   * @return
   */
  public static int yearDiffCurr(String after) {
    Date beforeDay = new Date();
    Date afterDay  = StringtoDate(after,LONG_DATE_FORMAT);
    return getYear(beforeDay)-getYear(afterDay);
  }
  
  public static int getFirstWeekdayOfMonth(int year, int month) {
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(Calendar.SATURDAY); 
    c.set(year, month - 1, 1);
    return c.get(Calendar.DAY_OF_WEEK);
  }

  public static int getLastWeekdayOfMonth(int year, int month) {
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(Calendar.SATURDAY); 
    c.set(year, month - 1, getDaysOfMonth(year, month));
    return c.get(Calendar.DAY_OF_WEEK);
  }


  /**
   * "yyyy-MM-dd HH:mm:ss"
   * @return
   */
  public static String getNow() {
    Calendar today = Calendar.getInstance();
    return DateToString(today.getTime(), FORMAT_ONE);
  }
    /**
     * "yyyyMMdd HH:mm:ss"
     * @return
     */
    public static Timestamp getCurrentTimestamp() {
        Calendar today = Calendar.getInstance();
        return new Timestamp(today.getTimeInMillis());
    }
    /**
     * "yyyyMMdd HH:mm:ss"
     * @return
     */
    public static Timestamp getTimestamp(String date) {
        return new Timestamp(StringtoDate(date,LONG_DATE_FORMAT).getTime());
    }
  /**
   * "yyyyMMdd HH:mm:ss"
   * @return
   */
  public static String getCurrentTime() {
    Calendar today = Calendar.getInstance();
    return DateToString(today.getTime(), FORMAT_THREE);
  }
  
  /**
   * @param date YYYY-mm-dd
   * @return
   */
  public static boolean isDate(String date){
    StringBuffer reg = new StringBuffer("^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
    reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
    reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
    reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
    reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
    reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
    reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
    reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
    Pattern p = Pattern.compile(reg.toString());
    return p.matcher(date).matches();
  }
  
	/**
	 * 
	 * @param date
	 * @param months
	 */
	public static Date nextMonth(Date date, int months) {
		Calendar cal = Calendar.getInstance();
		if (date != null) {
			cal.setTime(date);
		}
		cal.add(Calendar.MONTH, months);
		return cal.getTime();
	}

	/**
	 * 
	 * @param date
	 * @param day
	 */
	public static Date nextDay(Date date, int day) {
		Calendar cal = Calendar.getInstance();
		if (date != null) {
			cal.setTime(date);
		}
		cal.add(Calendar.DAY_OF_YEAR, day);
		return cal.getTime();
	}

	public static  Date getOneHoursAgoTime(Date date, int hour){
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.HOUR, hour);
        return cal.getTime();
    }
	/**
	 * @param day
	 * @return
	 */
	public static String nextDayBefore(String day) {
		day = "-"+day ;
		int dayInt = Integer.parseInt(day);
		Date nextDate = nextDay(new Date(),dayInt);
		return DateUtil.DateToString(nextDate, "yyyyMMdd");
	}
	/**
	 * 
	 * @param date
	 */
	public static Date nextWeek(Date date, int week) {
		Calendar cal = Calendar.getInstance();
		if (date != null) {
			cal.setTime(date);
		}
		cal.add(Calendar.WEEK_OF_MONTH, week);
		return cal.getTime();
	}

  /**
   * @return
   */
  public static String currDay() {
    return DateUtil.DateToString(new Date(),DateUtil.LONG_DATE_FORMAT);
  }
  /**
   * @return
   */
  public static String befoDay(){
    return DateUtil.DateToString(DateUtil.nextDay(new Date(),-1),DateUtil.LONG_DATE_FORMAT);
  }
  /**
   */
  public static String afterDay(){
    return afterDay(DateUtil.LONG_DATE_FORMAT);
  }
  /**
   * @param pattern
   * @return
   */
  public static String afterDay(String pattern) {
	  return DateUtil.DateToString(DateUtil.nextDay(new Date(),1),pattern);
  }
  
	/**
	 * @return
	 */
	public static int getDayNum(){
		int daynum = 0;
		GregorianCalendar gd = new GregorianCalendar();
		Date dt = gd.getTime();
		GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
		Date dt1 = gd1.getTime();
		daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
		return daynum;
	}
  
	/**
	 * @param day
	 * @return
	 */
	public static Date getDateByNum(int day){
		GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
		Date date=gd.getTime();
		date=nextDay(date,day);
		return date;
	}
	
	/**
	 * 
	 * 锟斤拷锟斤拷值: String
	 * @param 
	 * @throws
	 */
	public static String getTodayString(String mark) {
		SimpleDateFormat sdf = null;
		if("S".equals(mark)){
			sdf = new SimpleDateFormat("yyyyMMdd000001");
		}else if("E".equals(mark)){
			sdf = new SimpleDateFormat("yyyyMMdd235959");
		}else{
			sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		}
		Date date = new Date();
		return sdf.format(date);
	}
	
	/**
	 * 
	 * 锟斤拷锟斤拷值: String
	 * @param 
	 * @throws
	 */
	public static String getTodayyyyyMMdd() {
		SimpleDateFormat sdf = null;
		sdf = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		return sdf.format(date);
	}
	/**
	 * 
	 * 锟斤拷锟斤拷值: String
	 * @param 
	 * @throws
	 */
	public static String getTodayHHmmss() {
		SimpleDateFormat sdf = null;
		sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String dateStr = sdf.format(date);
		return dateStr.substring(8, 14);
	}
	/**
	 * 
	 * 锟斤拷锟斤拷值: String
	 * @param 
	 * @throws
	 */
	public static String getMonthF() {
		SimpleDateFormat sdf = null;
		sdf = new SimpleDateFormat("yyyyMM01");
		Date date = new Date();
		return sdf.format(date);
	}
	/**
	 * @return
	 */
	public static String getYearMonth() {
		SimpleDateFormat sdf = null;
		sdf = new SimpleDateFormat("yyyyMM");
		Date date = new Date();
		return sdf.format(date);	
	}

	/**
	 * @param dealDate
	 * @return
	 */
	public static String getNextDate(String dealDate) {
		Date nextDealDate = DateUtil.nextDay(DateUtil.StringtoDate(dealDate,"yyyyMMdd"),1);
		return  DateUtil.DateToString(nextDealDate, "yyyyMMdd");
	}
	/**
	 * @param dealDate
	 * @return
	 */
	public static boolean afterToDay(String dealDate) {
		String toDayStr = DateUtil.DateToString(new Date(), "yyyyMMdd");
		if(dealDate.compareTo(toDayStr)>0)
			return true;
		return false;
	}
	
	public static String timeMillisFormatDate(long timeMillis) {
		DateFormat formatter = new SimpleDateFormat(FORMAT_ONE);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(timeMillis);
		return formatter.format(calendar.getTime());
	}
	
	public static void main(String[] args) {
//		System.out.println(DateUtil.DateSub(-30));
//		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//		long now = 1505283045088L;
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTimeInMillis(now);
//		System.out.println(now + " = " + formatter.format(calendar.getTime()));

        System.out.println(DateUtil.getOneHoursAgoTime(new Date(),-1));


    }
}
